import 'dart:convert';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:http/http.dart' as http;
import 'package:get/get.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/models/assessment/assessmentCountResult.dart';
import 'package:ichinesereader/models/class/classSettingsResult.dart';
import 'package:ichinesereader/models/common/AuthMessage.dart';
import 'package:ichinesereader/models/common/LoginDto.dart';
import 'package:ichinesereader/models/common/LoginResult.dart';
import 'package:ichinesereader/models/common/MessageProperty.dart';
import 'package:ichinesereader/models/common/settings.dart';
import 'package:ichinesereader/models/individual/profileIndividual.dart';
import 'package:ichinesereader/models/individual/subscriptionUserDetails.dart';
import 'package:ichinesereader/models/parent/miniProfile.dart';
import 'package:ichinesereader/models/parent/profileParent.dart';
import 'package:ichinesereader/models/school/SchoolAdminProfile.dart';
import 'package:ichinesereader/models/student/ProfileStudent.dart';
import 'package:ichinesereader/models/teacher/ProfileTeacher.dart';
import 'package:ichinesereader/models/teacher/TeacherClass.dart';
import 'package:ichinesereader/service/user.dart';
import 'package:universal_html/html.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:hive_flutter/hive_flutter.dart';

class LoginController extends GetxController with CacheManager {
  final isLogged = false.obs;
  RxString _userName = ''.obs;
  RxString _userRole = ''.obs;
  RxString _authToken = ''.obs;
  RxString get userName => this._userName;
  RxString get userRole => this._userRole;
  RxString get authToken => this._authToken;

  final UserServiceProvider userServiceProvider = new UserServiceProvider();
  final box = Hive.box('appconfig');
  Future<AuthMessage> login(LoginDto logindto, bool remember) async {
    AuthMessage _authMessage = new AuthMessage();
    bool hasPlacement = false;
    try {
      EasyLoading.show();
      if (logindto.sessionType == null) logindto.sessionType = 'WEB';
      var response = await userServiceProvider.loginAsync(logindto);

      if (response.statusCode == 200) {
        LoginResult loginresult =
            LoginResult.fromJson(json.decode(response.body));

        if (loginresult.authToken != null && loginresult.user?.userId != null) {
          Settings settings = Settings();

          box.put('UserObjectId', loginresult.user?.userId ?? '');
          box.put(CacheManagerKey['username'].toString(),
              loginresult.user?.userName ?? '');
          box.put(CacheManagerKey['authtoken'].toString(),
              loginresult.authToken ?? '');
          box.put(CacheManagerKey['nanhairole'].toString(),
              loginresult.roles?[0] ?? '');

          if (remember) {
            savePassword(logindto.password.toString());
          } else {
            removePassword();
          }

          if (loginresult.user?.settings != null) {
            settings.audio = loginresult.user?.settings?.audio ?? false;
            settings.dictionary =
                loginresult.user?.settings?.dictionary ?? false;
            settings.id = loginresult.user?.settings?.id ?? '';
            settings.lang = loginresult.user?.settings?.lang ?? 'Mandarin';
            settings.language =
                loginresult.user?.settings?.language ?? 'Simplified';
            settings.music = loginresult.user?.settings?.music ?? false;
            settings.pinyin = loginresult.user?.settings?.pinyin ?? false;
            settings.quizAudio = loginresult.user?.settings?.quizAudio ?? false;
            settings.placementTest = true;
            settings.evaluation = true;
            settings.vocabulary = true;
            this.saveProfileSettings(json.encode(settings));
          }

          if (loginresult.user?.role?[0].toString() ==
              Constants.NanhaiRole_Student) {
            ProfileStudent? profile;

            if (loginresult.authToken != '') {
              var response =
                  await userServiceProvider.validateUser(loginresult.authToken);
              if (response.statusCode == 200) {
                profile = profileStudentFromJson(response.body);

                box.put("UserLevel", profile.level ?? '');
                box.put("UserName", loginresult.user?.userName ?? '');
                box.put("UserLevelPercentage", profile.levelPercentage ?? 0);
                box.put("UserPoints", profile.points?.toInt() ?? 0);
                box.put("UserNumBooks", profile.numBooks?.toInt() ?? 0);
                box.put("UserGender", profile.gender ?? '');
                box.put(
                    'UserLang', loginresult.user?.settings?.lang ?? 'Mandarin');
                box.put('UserLanguage',
                    loginresult.user?.settings?.language ?? 'Simplified');
                box.put(
                    'UserPinyin', loginresult.user?.settings?.pinyin ?? true);
                box.put('locale', profile.lang?.toInt() ?? 0);
                box.put('theme', profile.theme?.toInt() ?? 0);
                box.put(CacheManagerKey['profilesettings'].toString(),
                    json.encode(settings));

                if (GetPlatform.isWeb) {
                  document.cookie =
                      "nanhaiV4.8StudentUserId=${loginresult.user?.userName};path=/;SameSite=Strict;secure";
                  document.cookie =
                      "nanhaiV4.8Role=${loginresult.user?.role?[0].toString()};path=/;SameSite=Strict;secure";
                  document.cookie =
                      "nanhaiRole=${loginresult.user?.role?[0].toString()};path=/;SameSite=Strict;secure";
                  document.cookie =
                      "nanhaiIndividualSession=${loginresult.authToken};path=/;SameSite=Strict;secure";
                  document.cookie =
                      "nanhaiIndividualUserId=${loginresult.user?.userName};path=/;SameSite=Strict;secure";
                  document.cookie =
                      "nanhaiV4.8StudentSession=${loginresult.authToken};path=/;SameSite=Strict;secure";

                  window.sessionStorage['points'] =
                      profile.points?.toString() ?? '';
                  window.sessionStorage['numBooks'] =
                      profile.numBooks?.toString() ?? '';
                  window.sessionStorage['profileSettings'] =
                      json.encode(settings);
                  window.localStorage['level'] =
                      profile.level?.toString() ?? '';
                  window.localStorage['profileSettings'] =
                      json.encode(settings);
                  window.localStorage['locale'] =
                      profile.lang?.toString() ?? '0';
                  window.localStorage['theme'] =
                      profile.theme?.toString() ?? '0';
                  window.localStorage['userName'] =
                      '${loginresult.user?.userName}';
                  window.localStorage['lang'] =
                      '${loginresult.user?.settings?.lang ?? 'Mandarin'}';
                  window.localStorage['language'] =
                      '${loginresult.user?.settings?.language ?? 'Simplified'}';
                  window.localStorage['authToken'] =
                      '${loginresult.authToken ?? ''}';

                  if (window.localStorage['locale'] == '0')
                    window.localStorage['them_language'] = 'ENGLISH';
                  if (window.localStorage['locale'] == '1')
                    window.localStorage['them_language'] = 'SIMPLIFIED';
                  if (window.localStorage['locale'] == '2')
                    window.localStorage['them_language'] = 'TRADITIONAL';
                  if (window.localStorage['locale'] == '3')
                    window.localStorage['them_language'] = 'KOREAN';
                }

                var uresponse = await userServiceProvider.getClasses();
                if (uresponse.statusCode == 200) {
                  var classData = teacherClassFromJson(uresponse.bodyString);
                  if (classData.length > 0) {
                    //_userController.setCurrentStudentClass(classData[0]);
                    box.put(CacheManagerKey['currentclass'].toString(),
                        classData[0].classId.toString());

                    var cresponse =
                        await userServiceProvider.getClassSettingsByClassId(
                            classData[0].classId.toString());

                    if (cresponse.statusCode == 200) {
                      var csdataResult =
                          classSettingsResultFromJson(cresponse.bodyString);
                      if (csdataResult.result != null) {
                        settings.evaluation =
                            csdataResult.result?.evaluation ?? true;
                        settings.vocabulary =
                            csdataResult.result?.vocabulary ?? true;
                        settings.placementTest =
                            csdataResult.result?.placementTest ?? true;
                        profile.settings?.evaluation =
                            csdataResult.result?.evaluation ?? true;
                        profile.settings?.vocabulary =
                            csdataResult.result?.vocabulary ?? true;
                        profile.settings?.placementTest =
                            csdataResult.result?.placementTest ?? true;

                        box.put(CacheManagerKey['profilesettings'].toString(),
                            json.encode(settings));
                        this.saveProfileSettings(json.encode(settings));

                        if (profile.numBooks == 0 &&
                            settings.placementTest == true) {
                          var placementResponse =
                              await userServiceProvider.hasPlacementTest();
                          if (placementResponse.statusCode == 200) {
                            var data = assessmentCountResultFromJson(
                                placementResponse.body);
                            if (data.result != null) {
                              if (data.result!.count!.toInt() == 0) {
                                hasPlacement = true;
                                if (GetPlatform.isWeb) {
                                  document.cookie =
                                      "nanhaiV4.8NanhaiV4.8pretestDid=false;path=/;SameSite=Strict;secure";
                                }
                              } else {
                                if (GetPlatform.isWeb) {
                                  document.cookie =
                                      "nanhaiV4.8NanhaiV4.8pretestDid=true;path=/;SameSite=Strict;secure";
                                }
                              }
                            }
                          }
                        } else {
                          if (GetPlatform.isWeb) {
                            document.cookie =
                                "nanhaiV4.8NanhaiV4.8pretestDid=true;path=/;SameSite=Strict;secure";
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          } else if (loginresult.user?.role?[0].toString() ==
              Constants.NanhaiRole_Teacher) {
            ProfileTeacher? profile;
            if (loginresult.authToken != '') {
              var response =
                  await userServiceProvider.validateUser(loginresult.authToken);
              if (response.statusCode == 200) {
                profile = profileTeacherFromJson(response.body);
                settings.audio = profile.settings?.audio ?? false;
                settings.dictionary = profile.settings?.dictionary ?? false;
                settings.id = profile.settings?.id ?? '';
                settings.lang = profile.settings?.lang ?? 'Mandarin';
                settings.language = profile.settings?.language ?? 'Simplified';
                settings.music = profile.settings?.music ?? false;
                settings.pinyin = profile.settings?.pinyin ?? false;
                settings.quizAudio = profile.settings?.quizAudio ?? false;
              }
            }
            if (GetPlatform.isWeb) {
              window.sessionStorage['profileSettings'] = json.encode(settings);
              window.sessionStorage['nanhaiV4.8LevelOptions'] =
                  Constants.LevelColorJson;

              document.cookie =
                  "nanhaiV4.8TeacherSession=${loginresult.authToken};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiV4.8TeacherUserId=${loginresult.user?.userName};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiTeacherSession=${loginresult.authToken};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiTeacherUserId=${loginresult.user?.userName};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiV4.8Role=${loginresult.user?.role?[0].toString()};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiRole=${loginresult.user?.role?[0].toString()};path=/;SameSite=Strict;secure";

              window.localStorage['locale'] = profile?.lang.toString() ?? '0';
              window.localStorage['theme'] = profile?.theme.toString() ?? '0';
              window.localStorage['userName'] = '${loginresult.user?.userName}';
              window.localStorage['authToken'] =
                  '${loginresult.authToken ?? ''}';
              box.put(
                  'UserLang', loginresult.user?.settings?.lang ?? 'Mandarin');
              box.put('UserLanguage',
                  loginresult.user?.settings?.language ?? 'Simplified');
              box.put('UserPinyin', loginresult.user?.settings?.pinyin ?? true);
              box.put(CacheManagerKey['profilesettings'].toString(),
                  json.encode(settings));
              if (window.localStorage['locale'] == '0')
                window.localStorage['them_language'] = 'ENGLISH';
              if (window.localStorage['locale'] == '1')
                window.localStorage['them_language'] = 'SIMPLIFIED';
              if (window.localStorage['locale'] == '2')
                window.localStorage['them_language'] = 'TRADITIONAL';
              if (window.localStorage['locale'] == '3')
                window.localStorage['them_language'] = 'KOREAN';
            } else {
              box.put(
                  'UserLang', loginresult.user?.settings?.lang ?? 'Mandarin');
              box.put('UserLanguage',
                  loginresult.user?.settings?.language ?? 'Simplified');
              box.put('UserPinyin', loginresult.user?.settings?.pinyin ?? true);
              box.put(CacheManagerKey['profilesettings'].toString(),
                  json.encode(settings));
              box.put("nanhaiV4.8LevelOptions", Constants.LevelColorJson);
              box.put('locale', profile?.lang?.toInt() ?? 0);
              box.put('theme', profile?.theme?.toInt() ?? 0);
            }

            if (loginresult.message == 'Password need to be reset') {
              _authMessage.status = LoginStatusKey.need_strong_password;
              _authMessage.message = 'Password need to be reset';
              return _authMessage;
            }
          } else if (loginresult.user?.role?[0].toString() ==
              Constants.NanhaiRole_Individual) {
            ProfileIndividual? profile;

            var response =
                await userServiceProvider.validateUser(loginresult.authToken);
            if (response.statusCode == 200) {
              profile = profileIndividualFromJson(response.body);
            }

            if (GetPlatform.isWeb) {
              document.cookie =
                  "nanhaiV4.8IndividualSession=${loginresult.authToken};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiV4.8IndividualUserId=${loginresult.user?.userName};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiV4.8Role=${loginresult.user?.role?[0].toString()};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiRole=${loginresult.user?.role?[0].toString()};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiIndividualSession=${loginresult.authToken};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiIndividualUserId=${loginresult.user?.userName};path=/;SameSite=Strict;secure";

              window.sessionStorage['profileSettings'] = json.encode(settings);
              window.sessionStorage['points'] =
                  profile?.points.toString() ?? '';
              window.sessionStorage['numBooks'] =
                  profile?.numBooks?.toString() ?? '';
              window.localStorage['level'] = profile?.level?.toString() ?? '';
              window.localStorage['locale'] = profile?.lang.toString() ?? '0';
              window.localStorage['theme'] = profile?.theme.toString() ?? '0';
              window.localStorage['authToken'] =
                  '${loginresult.authToken ?? ''}';
              window.localStorage['lang'] =
                  '${loginresult.user?.settings?.lang ?? 'Mandarin'}';
              window.localStorage['language'] =
                  '${loginresult.user?.settings?.language ?? 'Simplified'}';
              window.localStorage['userName'] = '${loginresult.user?.userName}';
              box.put(
                  'UserLang', loginresult.user?.settings?.lang ?? 'Mandarin');
              box.put('UserLanguage',
                  loginresult.user?.settings?.language ?? 'Simplified');
              box.put('UserPinyin', loginresult.user?.settings?.pinyin ?? true);
              box.put("UserLevel", profile?.level ?? '');
              box.put("UserLevelPercentage", profile?.levelPercentage ?? 0);
              box.put(CacheManagerKey['profilesettings'].toString(),
                  json.encode(settings));
              box.put("UserPoints", profile?.points?.toInt() ?? 0);
              if (window.localStorage['locale'] == '0')
                window.localStorage['them_language'] = 'ENGLISH';
              if (window.localStorage['locale'] == '1')
                window.localStorage['them_language'] = 'SIMPLIFIED';
              if (window.localStorage['locale'] == '2')
                window.localStorage['them_language'] = 'TRADITIONAL';
              if (window.localStorage['locale'] == '3')
                window.localStorage['them_language'] = 'KOREAN';
            } else {
              box.put(CacheManagerKey['profilesettings'].toString(),
                  json.encode(settings));
              box.put("UserLevel", profile?.level ?? '');
              box.put("UserLevelPercentage", profile?.levelPercentage ?? 0);
              box.put("UserPoints", profile?.points?.toInt() ?? 0);
              box.put("UserNumBooks", profile?.numBooks?.toInt() ?? 0);
              box.put(
                  'UserLang', loginresult.user?.settings?.lang ?? 'Mandarin');
              box.put('UserLanguage',
                  loginresult.user?.settings?.language ?? 'Simplified');
              box.put('UserPinyin', loginresult.user?.settings?.pinyin ?? true);
              box.put('locale', profile?.lang?.toInt() ?? 0);
              box.put('theme', profile?.theme?.toInt() ?? 0);
            }

            if (profile?.numBooks == 0) {
              var placementResponse =
                  await userServiceProvider.hasPlacementTest();
              if (placementResponse.statusCode == 200) {
                var data =
                    assessmentCountResultFromJson(placementResponse.body);
                if (data.result != null) {
                  if (data.result!.count!.toInt() == 0) {
                    hasPlacement = true;
                    if (GetPlatform.isWeb) {
                      document.cookie =
                          "nanhaiV4.8NanhaiV4.8pretestDid=false;path=/;SameSite=Strict;secure";
                    }
                  } else {
                    if (GetPlatform.isWeb) {
                      document.cookie =
                          "nanhaiV4.8NanhaiV4.8pretestDid=true;path=/;SameSite=Strict;secure";
                    }
                  }
                }
              }
            } else {
              if (GetPlatform.isWeb) {
                document.cookie =
                    "nanhaiV4.8NanhaiV4.8pretestDid=true;path=/;SameSite=Strict;secure";
              }
            }
          } else if (loginresult.user?.role?[0].toString() ==
              Constants.NanhaiRole_Parent) {
            ProfileParent? profile;

            userServiceProvider
                .validateUser(loginresult.authToken)
                .then((response) {
              if (response.statusCode == 200) {
                profile = profileParentFromJson(response.body);

                var mProfile = MiniProfile();
                if (profile?.userId != null) {
                  mProfile.firstName = profile?.firstName;
                  mProfile.lastName = profile?.lastName;
                  mProfile.email = profile?.email;
                }

                if (GetPlatform.isWeb) {
                  document.cookie =
                      "nanhaiV4.8ParentSession=${loginresult.authToken};path=/;SameSite=Strict;secure";
                  document.cookie =
                      "nanhaiV4.8ParentUserId=${loginresult.user?.userName};path=/;SameSite=Strict;secure";
                  document.cookie =
                      "nanhaiV4.8Role=${loginresult.user?.role?[0].toString()};path=/;SameSite=Strict;secure";
                  document.cookie =
                      "nanhaiRole=${loginresult.user?.role?[0].toString()};path=/;SameSite=Strict;secure";

                  window.sessionStorage['profile'] = json.encode(mProfile);
                  window.localStorage['locale'] = '0';
                  window.localStorage['theme'] = '0';
                  if (window.localStorage['locale'] == '0')
                    window.localStorage['them_language'] = 'ENGLISH';
                  if (window.localStorage['locale'] == '1')
                    window.localStorage['them_language'] = 'SIMPLIFIED';
                  if (window.localStorage['locale'] == '2')
                    window.localStorage['them_language'] = 'TRADITIONAL';
                  if (window.localStorage['locale'] == '3')
                    window.localStorage['them_language'] = 'KOREAN';
                } else {
                  box.put(CacheManagerKey['profilesettings'].toString(),
                      json.encode(mProfile));
                  box.put('locale', 0);
                  box.put('theme', 0);
                }
              }
            });
          } else if (loginresult.user?.role?[0].toString() ==
              Constants.NanhaiRole_SchoolAdmin) {
            SchoolAdminProfile? profile;

            var response =
                await userServiceProvider.validateUser(loginresult.authToken);
            if (response.statusCode == 200) {
              profile = schoolAdminProfileFromJson(response.body);
            }

            if (GetPlatform.isWeb) {
              document.cookie =
                  "nanhaiV4.8SchooladminSession=${loginresult.authToken};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiV4.8SchooladminUserId=${loginresult.user?.userName};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiSchooladminSession=${loginresult.authToken};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiSchooladminUserId=${loginresult.user?.userName};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiV4.8Role=${loginresult.user?.role?[0].toString()};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiRole=${loginresult.user?.role?[0].toString()};path=/;SameSite=Strict;secure";

              window.localStorage['locale'] = profile?.lang.toString() ?? '0';
              window.localStorage['theme'] = profile?.theme.toString() ?? '0';
              box.put(
                  'UserLang', loginresult.user?.settings?.lang ?? 'Mandarin');
              box.put('UserLanguage',
                  loginresult.user?.settings?.language ?? 'Simplified');
              box.put('UserPinyin', loginresult.user?.settings?.pinyin ?? true);
              if (window.localStorage['locale'] == '0')
                window.localStorage['them_language'] = 'ENGLISH';
              if (window.localStorage['locale'] == '1')
                window.localStorage['them_language'] = 'SIMPLIFIED';
              if (window.localStorage['locale'] == '2')
                window.localStorage['them_language'] = 'TRADITIONAL';
              if (window.localStorage['locale'] == '3')
                window.localStorage['them_language'] = 'KOREAN';
            } else {
              box.put('locale', profile?.lang?.toInt() ?? 0);
              box.put('theme', profile?.theme?.toInt() ?? 0);
              box.put(
                  'UserLang', loginresult.user?.settings?.lang ?? 'Mandarin');
              box.put('UserLanguage',
                  loginresult.user?.settings?.language ?? 'Simplified');
              box.put('UserPinyin', loginresult.user?.settings?.pinyin ?? true);
            }
            if (loginresult.message == 'Password need to be reset') {
              _authMessage.status = LoginStatusKey.need_strong_password;
              _authMessage.message = 'Password need to be reset';
              return _authMessage;
            }
          } else {
            Get.offAllNamed('/login');
          }

          this._userRole.value = loginresult.user?.role?[0].toString() ?? '';
          this._userName.value = loginresult.user?.userName ?? '';
          this._authToken.value = loginresult.authToken ?? '';
          this.isLogged.value = true;

          loginCache(loginresult.user?.userName, loginresult.authToken,
              loginresult.user?.role?[0].toString());

          Log.debug(loginresult.authToken);

          _authMessage.status = LoginStatusKey.logged_in;

          //判断是否需要做前测
          if (hasPlacement) {
            _authMessage.status = LoginStatusKey.has_placement;
          }

          _authMessage.message = loginresult.message;
          return _authMessage;
        } else {
          _authMessage.status = LoginStatusKey.logged_out;
          _authMessage.message = loginresult.message;

          if (_authMessage.message ==
              'Account Expired/Subscription Cancelled') {
            SubscriptionUserDetails subscription = SubscriptionUserDetails();
            subscription.braintreeCustomerId = loginresult.user?.userId ?? '';
            subscription.email = loginresult.user?.email ?? '';
            subscription.firstName = loginresult.user?.firstName ?? '';
            subscription.lastName = loginresult.user?.lastName ?? '';
            subscription.userName = loginresult.user?.userName ?? '';

            if (GetPlatform.isWeb) {
              document.cookie =
                  "nanhaiV4.8IndividualUserId=${loginresult.user?.userName};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiIndividualUserId=${loginresult.user?.userName};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiV4.8UserDetails=${subscriptionUserDetailsToJson(subscription)};path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiV4.8IndividualSession=;path=/;SameSite=Strict;secure";
              document.cookie = "nanhaiV4.8Role=;path=/;SameSite=Strict;secure";
              document.cookie = "nanhaiRole=;path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiIndividualSession=;path=/;SameSite=Strict;secure";
            } else {
              box.put('nanhaiV4.8UserDetails',
                  '${subscriptionUserDetailsToJson(subscription)}');
              box.put(CacheManagerKey['username'].toString(),
                  loginresult.user?.userName ?? '');
              box.put(CacheManagerKey['authtoken'].toString(),
                  loginresult.authToken ?? '');
              box.put(CacheManagerKey['nanhairole'].toString(),
                  loginresult.roles?[0] ?? '');

              CookieManager cookieManager = CookieManager.instance();
              final expiresDate =
                  DateTime.now().add(Duration(days: 3)).millisecondsSinceEpoch;
              await cookieManager.deleteAllCookies();

              await cookieManager.setCookie(
                url: WebUri(Constants.BaseURL),
                name: "nanhaiV4.8IndividualUserId",
                value: box.get(CacheManagerKey['username'].toString()) ?? '',
                domain: Constants.BaseDomain,
                path: '/',
                expiresDate: expiresDate,
                isSecure: true,
              );
              await cookieManager.setCookie(
                url: WebUri(Constants.BaseURL),
                name: "nanhaiV4.8UserDetails",
                value: '${subscriptionUserDetailsToJson(subscription)}',
                domain: Constants.BaseDomain,
                path: '/',
                expiresDate: expiresDate,
                isSecure: true,
              );
            }
            //Log.debug('${subscriptionUserDetailsToJson(subscription)}');
          }
          return _authMessage;
        }
      } else if (response.statusCode == 422) {
        this.isLogged.value = false;
        MessagePropertyResult mp = messagePropertyResultFromJson(response.body);

        if (mp.message != null) {
          _authMessage.status = LoginStatusKey.expired;
          _authMessage.message = mp.message?.message;
        } else {
          _authMessage.status = LoginStatusKey.error;
          _authMessage.message = mp.message.toString();
        }
        //this.removeToken();
        return _authMessage;
      } else if (response.statusCode == 403) {
        //this.removeToken();
        this.isLogged.value = false;
        MessagePropertyResult mp = messagePropertyResultFromJson(response.body);

        if (mp.message != null) {
          _authMessage.status = LoginStatusKey.session_timeout;
          _authMessage.message = mp.message?.message;
        } else {
          _authMessage.status = LoginStatusKey.error;
          _authMessage.message = mp.message.toString();
        }
        return _authMessage;
      } else {
        //this.removeToken();
        this.isLogged.value = false;
        _authMessage.status = LoginStatusKey.error;
        _authMessage.message = response.statusCode.toString();
        return _authMessage;
      }
    } catch (error) {
      //this.removeToken();
      this.isLogged.value = false;
      _authMessage.status = LoginStatusKey.error;
      Log.debug('Oops, something wrong ...'.tr);
      _authMessage.message = 'Log in failure, please try again!'.tr;
      return _authMessage;
    } finally {
      EasyLoading.dismiss();
    }
  }

  Future<AuthMessage> checkLoginStatus() async {
    AuthMessage _authMessage = new AuthMessage();
    //var unescape = HtmlUnescape();
    bool hasPlacement = false;
    String _userName = GetPlatform.isWeb
        ? this.getWebUsername().toString()
        : this.getUsername().toString();
    String _userRole = GetPlatform.isWeb
        ? this.getWebRole().toString()
        : this.getRole().toString();
    String _authToken = GetPlatform.isWeb
        ? this.getWebToken().toString()
        : this.getToken().toString();

    try {
      if (_userName != '' && _userRole != '' && _authToken != '') {
        _authToken = _authToken.replaceAll('%3D', '=');
        _userName = _userName.replaceAll('%40', '@');
        http.Response response =
            await userServiceProvider.validateUser(_authToken);
        if (response.statusCode == 200) {
          Settings settings = Settings();

          box.put(CacheManagerKey['username'].toString(), _userName);
          box.put(CacheManagerKey['authtoken'].toString(), _authToken);
          box.put(CacheManagerKey['nanhairole'].toString(), _userRole);
          this._userName.value = _userName;
          this._userRole.value = _userRole;
          this._authToken.value = _authToken;
          this.isLogged.value = true;

          if (_userRole == Constants.NanhaiRole_Student) {
            if (response.statusCode == 200) {
              ProfileStudent? profile;
              profile = profileStudentFromJson(response.body);

              if (profile.settings != null) {
                settings.audio = profile.settings?.audio ?? false;
                settings.dictionary = profile.settings?.dictionary ?? false;
                settings.id = profile.settings?.id ?? '';
                settings.lang = profile.settings?.lang ?? 'Mandarin';
                settings.language = profile.settings?.language ?? 'Simplified';
                settings.music = profile.settings?.music ?? false;
                settings.pinyin = profile.settings?.pinyin ?? false;
                settings.quizAudio = profile.settings?.quizAudio ?? false;
                this.saveProfileSettings(json.encode(settings));
              }

              box.put("UserLevel", profile.level ?? '');
              box.put("UserLevelPercentage", profile.levelPercentage ?? 0);
              box.put("UserPoints", profile.points?.toInt() ?? 0);
              box.put("UserNumBooks", profile.numBooks?.toInt() ?? 0);
              box.put("UserGender", profile.gender ?? '');
              box.put('UserLang', profile.settings?.lang ?? 'Mandarin');
              box.put(
                  'UserLanguage', profile.settings?.language ?? 'Simplified');
              box.put('UserPinyin', profile.settings?.pinyin ?? true);
              box.put('locale', profile.lang?.toInt() ?? 0);
              box.put('theme', profile.theme?.toInt() ?? 0);
              box.put(CacheManagerKey['profilesettings'].toString(),
                  json.encode(settings));

              if (GetPlatform.isWeb) {
                document.cookie =
                    "nanhaiV4.8StudentSession=$_authToken;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiV4.8StudentUserId=$_userName;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiStudentSession=$_authToken;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiStudentUserId=$_userName;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiV4.8Role=$_userRole;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiRole=$_userRole;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiIndividualSession=$_authToken;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiIndividualUserId=$_userName;path=/;SameSite=Strict;secure";
                window.sessionStorage['points'] =
                    profile.points?.toString() ?? '';
                window.localStorage['level'] = profile.level?.toString() ?? '';
                window.sessionStorage['numBooks'] =
                    profile.numBooks?.toString() ?? '';
                window.sessionStorage['profileSettings'] =
                    json.encode(settings);
                window.localStorage['profileSettings'] = json.encode(settings);
                window.localStorage['locale'] = profile.lang?.toString() ?? '0';
                window.localStorage['theme'] = profile.theme?.toString() ?? '0';
                window.localStorage['userName'] = _userName;
                window.localStorage['lang'] =
                    '${profile.settings?.lang ?? 'Mandarin'}';
                window.localStorage['language'] =
                    '${profile.settings?.language ?? 'Simplified'}';
                window.localStorage['authToken'] = _authToken;

                if (window.localStorage['locale'] == '0')
                  window.localStorage['them_language'] = 'ENGLISH';
                if (window.localStorage['locale'] == '1')
                  window.localStorage['them_language'] = 'SIMPLIFIED';
                if (window.localStorage['locale'] == '2')
                  window.localStorage['them_language'] = 'TRADITIONAL';
                if (window.localStorage['locale'] == '3')
                  window.localStorage['them_language'] = 'KOREAN';
              }

              var uresponse = await userServiceProvider.getClasses();

              if (uresponse.statusCode == 200) {
                var classData = teacherClassFromJson(uresponse.bodyString);
                if (classData.length > 0) {
                  box.put(CacheManagerKey['currentclass'].toString(),
                      classData[0].classId.toString());

                  var cresponse =
                      await userServiceProvider.getClassSettingsByClassId(
                          classData[0].classId.toString());
                  if (cresponse.statusCode == 200) {
                    var csdataResult =
                        classSettingsResultFromJson(cresponse.bodyString);
                    if (csdataResult.result != null) {
                      settings.evaluation =
                          csdataResult.result?.evaluation ?? true;
                      settings.vocabulary =
                          csdataResult.result?.vocabulary ?? true;
                      settings.placementTest =
                          csdataResult.result?.placementTest ?? true;
                      profile.settings?.evaluation =
                          csdataResult.result?.evaluation ?? true;
                      profile.settings?.vocabulary =
                          csdataResult.result?.vocabulary ?? true;
                      profile.settings?.placementTest =
                          csdataResult.result?.placementTest ?? true;

                      box.put(CacheManagerKey['profilesettings'].toString(),
                          json.encode(settings));
                      this.saveProfileSettings(json.encode(settings));

                      if (profile.numBooks == 0 &&
                          settings.placementTest == true) {
                        var placementResponse =
                            await userServiceProvider.hasPlacementTest();
                        if (placementResponse.statusCode == 200) {
                          var data = assessmentCountResultFromJson(
                              placementResponse.body);
                          if (data.result != null) {
                            if (data.result!.count!.toInt() == 0) {
                              hasPlacement = true;
                              if (GetPlatform.isWeb) {
                                document.cookie =
                                    "nanhaiV4.8NanhaiV4.8pretestDid=false;path=/;SameSite=Strict;secure";
                              }
                            } else {
                              if (GetPlatform.isWeb) {
                                document.cookie =
                                    "nanhaiV4.8NanhaiV4.8pretestDid=true;path=/;SameSite=Strict;secure";
                              }
                            }
                          }
                        }
                      } else {
                        if (GetPlatform.isWeb) {
                          document.cookie =
                              "nanhaiV4.8NanhaiV4.8pretestDid=true;path=/;SameSite=Strict;secure";
                        }
                      }
                    }
                  }
                }
              }
            }
          } else if (_userRole == Constants.NanhaiRole_Teacher) {
            if (response.statusCode == 200) {
              ProfileTeacher profile = profileTeacherFromJson(response.body);

              if (profile.settings != null) {
                settings.audio = profile.settings?.audio ?? false;
                settings.dictionary = profile.settings?.dictionary ?? false;
                settings.id = profile.settings?.id ?? '';
                settings.lang = profile.settings?.lang ?? 'Mandarin';
                settings.language = profile.settings?.language ?? 'Simplified';
                settings.music = profile.settings?.music ?? false;
                settings.pinyin = profile.settings?.pinyin ?? false;
                settings.quizAudio = profile.settings?.quizAudio ?? false;
                this.saveProfileSettings(json.encode(settings));
              }

              if (GetPlatform.isWeb) {
                window.sessionStorage['profileSettings'] =
                    json.encode(settings);
                window.sessionStorage['nanhaiV4.8LevelOptions'] =
                    Constants.LevelColorJson;
                document.cookie =
                    "nanhaiRole=$_userRole;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiTeacherSession=$_authToken;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiTeacherUserId=$_userName;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiV4.8Role=$_userRole;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiV4.8TeacherSession=$_authToken;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiV4.8TeacherUserId=$_userName;path=/;SameSite=Strict;secure";
                window.localStorage['locale'] = profile.lang.toString();
                window.localStorage['theme'] = profile.theme.toString();
                window.localStorage['userName'] = '$_userName';
                window.localStorage['authToken'] = '$_authToken';
                box.put('UserLang', profile.settings?.lang ?? 'Mandarin');
                box.put(
                    'UserLanguage', profile.settings?.language ?? 'Simplified');
                box.put('UserPinyin', profile.settings?.pinyin ?? true);
                box.put(CacheManagerKey['profilesettings'].toString(),
                    json.encode(settings));
                if (window.localStorage['locale'] == '0')
                  window.localStorage['them_language'] = 'ENGLISH';
                if (window.localStorage['locale'] == '1')
                  window.localStorage['them_language'] = 'SIMPLIFIED';
                if (window.localStorage['locale'] == '2')
                  window.localStorage['them_language'] = 'TRADITIONAL';
                if (window.localStorage['locale'] == '3')
                  window.localStorage['them_language'] = 'KOREAN';
              } else {
                box.put('UserLang', profile.settings?.lang ?? 'Mandarin');
                box.put(
                    'UserLanguage', profile.settings?.language ?? 'Simplified');
                box.put('UserPinyin', profile.settings?.pinyin ?? true);
                box.put(CacheManagerKey['profilesettings'].toString(),
                    json.encode(settings));
                box.put("nanhaiV4.8LevelOptions", Constants.LevelColorJson);
                box.put('locale', profile.lang?.toInt() ?? 0);
                box.put('theme', profile.theme?.toInt() ?? 0);
              }
            }
          } else if (_userRole == Constants.NanhaiRole_Individual) {
            if (response.statusCode == 200) {
              ProfileIndividual profile =
                  profileIndividualFromJson(response.body);

              if (GetPlatform.isWeb) {
                document.cookie =
                    "nanhaiV4.8IndividualSession=$_authToken;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiV4.8IndividualUserId=$_userName;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiV4.8Role=$_userRole;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiRole=$_userRole;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiIndividualSession=$_authToken;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiIndividualUserId=$_userName;path=/;SameSite=Strict;secure";

                window.localStorage['level'] = profile.level?.toString() ?? '';
                window.sessionStorage['points'] =
                    profile.points?.toString() ?? '';
                window.sessionStorage['numBooks'] =
                    profile.numBooks?.toString() ?? '';
                window.localStorage['locale'] = profile.lang?.toString() ?? '0';
                window.localStorage['theme'] = profile.theme?.toString() ?? '0';
                window.localStorage['userName'] = _userName;
                window.localStorage['lang'] = '${profile.lang ?? 'Mandarin'}';
                window.localStorage['language'] =
                    '${profile.language ?? 'Simplified'}';
                box.put("UserLevel", profile.level ?? '');
                box.put("UserPoints", profile.points?.toInt() ?? 0);
                box.put("UserNumBooks", profile.numBooks?.toInt() ?? 0);
                box.put('UserLang', profile.settings?.lang ?? 'Mandarin');
                box.put(
                    'UserLanguage', profile.settings?.language ?? 'Simplified');
                box.put('UserPinyin', profile.settings?.pinyin ?? true);
                box.put(CacheManagerKey['profilesettings'].toString(),
                    json.encode(settings));
                if (window.localStorage['locale'] == '0')
                  window.localStorage['them_language'] = 'ENGLISH';
                if (window.localStorage['locale'] == '1')
                  window.localStorage['them_language'] = 'SIMPLIFIED';
                if (window.localStorage['locale'] == '2')
                  window.localStorage['them_language'] = 'TRADITIONAL';
                if (window.localStorage['locale'] == '3')
                  window.localStorage['them_language'] = 'KOREAN';
              } else {
                box.put("UserLevel", profile.level ?? '');
                box.put("UserPoints", profile.points?.toInt() ?? 0);
                box.put("UserNumBooks", profile.numBooks?.toInt() ?? 0);
                box.put("UserGender", profile.gender ?? '');
                box.put('locale', profile.lang?.toInt() ?? 0);
                box.put('theme', profile.theme?.toInt() ?? 0);
                box.put('UserLang', profile.settings?.lang ?? 'Mandarin');
                box.put(
                    'UserLanguage', profile.settings?.language ?? 'Simplified');
                box.put('UserPinyin', profile.settings?.pinyin ?? true);
                box.put(CacheManagerKey['profilesettings'].toString(),
                    json.encode(settings));
              }
              if (profile.numBooks == 0) {
                var placementResponse =
                    await userServiceProvider.hasPlacementTest();
                if (placementResponse.statusCode == 200) {
                  var data =
                      assessmentCountResultFromJson(placementResponse.body);
                  if (data.result != null) {
                    if (data.result!.count!.toInt() == 0) {
                      hasPlacement = true;
                      if (GetPlatform.isWeb) {
                        document.cookie =
                            "nanhaiV4.8NanhaiV4.8pretestDid=false;path=/;SameSite=Strict;secure";
                      }
                    } else {
                      if (GetPlatform.isWeb) {
                        document.cookie =
                            "nanhaiV4.8NanhaiV4.8pretestDid=true;path=/;SameSite=Strict;secure";
                      }
                    }
                  }
                }
              } else {
                if (GetPlatform.isWeb) {
                  document.cookie =
                      "nanhaiV4.8NanhaiV4.8pretestDid=true;path=/;SameSite=Strict;secure";
                }
              }
            }
          } else if (_userRole == Constants.NanhaiRole_Parent) {
            ProfileParent? profile;

            if (response.statusCode == 200) {
              profile = profileParentFromJson(response.body);

              var mProfile = MiniProfile();
              if (profile.userId != null) {
                mProfile.firstName = profile.firstName;
                mProfile.lastName = profile.lastName;
                mProfile.email = profile.email;
              }

              if (GetPlatform.isWeb) {
                document.cookie =
                    "nanhaiV4.8ParentSession=$_authToken;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiV4.8ParentUserId=$_userName;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiV4.8Role=$_userRole;path=/;SameSite=Strict;secure";
                document.cookie =
                    "nanhaiRole=$_userRole;path=/;SameSite=Strict;secure";

                window.sessionStorage['profile'] = json.encode(mProfile);
                window.localStorage['locale'] = '0';
                window.localStorage['theme'] = '0';
                if (window.localStorage['locale'] == '0')
                  window.localStorage['them_language'] = 'ENGLISH';
                if (window.localStorage['locale'] == '1')
                  window.localStorage['them_language'] = 'SIMPLIFIED';
                if (window.localStorage['locale'] == '2')
                  window.localStorage['them_language'] = 'TRADITIONAL';
                if (window.localStorage['locale'] == '3')
                  window.localStorage['them_language'] = 'KOREAN';
              } else {
                box.put(CacheManagerKey['profilesettings'].toString(),
                    json.encode(mProfile));
                box.put('locale', 0);
                box.put('theme', 0);
              }
            }
          } else if (_userRole == Constants.NanhaiRole_SchoolAdmin) {
            SchoolAdminProfile? profile;
            if (response.statusCode == 200) {
              profile = schoolAdminProfileFromJson(response.body);
            }
            if (GetPlatform.isWeb) {
              document.cookie =
                  "nanhaiSchooladminSession=$_authToken;path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiSchooladminUserId=$_userName;path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiV4.8SchooladminSession=$_authToken;path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiV4.8SchooladminUserId=$_userName;path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiV4.8Role=$_userRole;path=/;SameSite=Strict;secure";
              document.cookie =
                  "nanhaiRole=$_userRole;path=/;SameSite=Strict;secure";

              window.localStorage['locale'] = profile?.lang.toString() ?? '0';
              window.localStorage['theme'] = profile?.theme.toString() ?? '0';
              if (window.localStorage['locale'] == '0')
                window.localStorage['them_language'] = 'ENGLISH';
              if (window.localStorage['locale'] == '1')
                window.localStorage['them_language'] = 'SIMPLIFIED';
              if (window.localStorage['locale'] == '2')
                window.localStorage['them_language'] = 'TRADITIONAL';
              if (window.localStorage['locale'] == '3')
                window.localStorage['them_language'] = 'KOREAN';
            } else {
              box.put('locale', profile?.lang?.toInt() ?? 0);
              box.put('theme', profile?.theme?.toInt() ?? 0);
              box.put('UserLang', profile?.settings?.lang ?? 'Mandarin');
              box.put(
                  'UserLanguage', profile?.settings?.language ?? 'Simplified');
              box.put('UserPinyin', profile?.settings?.pinyin ?? true);
            }
          } else {}

          _authMessage.status = LoginStatusKey.logged_in;
          //判断是否需要做前测
          if (hasPlacement) {
            _authMessage.status = LoginStatusKey.has_placement;
          }

          _authMessage.message = 'Login success';
          return _authMessage;
        } else {
          this.removeProfileSettings();
          this.isLogged.value = false;
          _authMessage.status = LoginStatusKey.error;
          _authMessage.message = response.statusCode.toString();
          return _authMessage;
        }
      } else {
        this.removeProfileSettings();
        this.isLogged.value = false;
        _authMessage.status = LoginStatusKey.logged_out;
        _authMessage.message = 'not logged in';
        return _authMessage;
      }
    } catch (error) {
      this.removeProfileSettings();
      this.isLogged.value = false;
      _authMessage.status = LoginStatusKey.error;
      _authMessage.message = 'Oops, something wrong ...'.tr;
      return _authMessage;
    } finally {}
  }

  void clearCache() {
    try {
      String role = box.get(CacheManagerKey['nanhairole'].toString());
      _userName.value = '';
      _userRole.value = '';
      _authToken.value = '';
      box.delete(CacheManagerKey['profilesettings'].toString());
      box.delete(CacheManagerKey['authtoken'].toString());
      box.delete(CacheManagerKey['nanhairole'].toString());
      isLogged.value = false;

      if (GetPlatform.isWeb) {
        Log.debug('clear browser caches');
        window.localStorage.clear();
        window.sessionStorage.clear();
        document.cookie = "nanhaiV4.8Role=;path=/;SameSite=Strict;secure";
        document.cookie = "nanhaiRole=;path=/;SameSite=Strict;secure";

        if (role == Constants.NanhaiRole_Individual) {
          document.cookie =
              "nanhaiIndividualSession=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiIndividualUserId=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiV4.8IndividualSession=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiV4.8IndividualUserId=;path=/;SameSite=Strict;secure";
        }

        if (role == Constants.NanhaiRole_Student) {
          document.cookie =
              "nanhaiIndividualSession=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiIndividualUserId=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiV4.8StudentSession=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiV4.8StudentUserId=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiStudentSession=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiStudentUserId=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiV4.8NanhaiV4.8pretestDid=;path=/;SameSite=Strict;secure";
        }

        if (role == Constants.NanhaiRole_SchoolAdmin) {
          document.cookie =
              "nanhaiSchooladminSession=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiSchooladminUserId=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiV4.8SchooladminSession=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiV4.8SchooladminUserId=;path=/;SameSite=Strict;secure";
        }

        if (role == Constants.NanhaiRole_Parent) {
          document.cookie =
              "nanhaiParentSession=;path=/;SameSite=Strict;secure";
          document.cookie = "nanhaiParentUserId=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiV4.8ParentSession=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiV4.8ParentUserId=;path=/;SameSite=Strict;secure";
        }

        if (role == Constants.NanhaiRole_Teacher) {
          document.cookie =
              "nanhaiTeacherSession=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiTeacherUserId=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiV4.8TeacherSession=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiV4.8TeacherUserId=;path=/;SameSite=Strict;secure";
          document.cookie =
              "nanhaiV4.8TeacherClassSelected=;path=/;SameSite=Strict;secure";
        }
      } else {
        var cookies = CookieManager.instance();
        cookies.deleteAllCookies();
      }
    } catch (error) {
      Log.debug('log out error: $error');
    }
  }

  void logOut() async {
    userServiceProvider.logoutAsync();
    clearCache();
  }

  void loginCache(String? username, String? token, String? role) async {
    isLogged.value = true;
    _userName.value = username ?? '';
    _userRole.value = role ?? '';
    _authToken.value = token ?? '';
    await saveToken(username, token, role);
  }

  @override
  dispose() {
    super.dispose();
  }
}

enum LoginStatusKey {
  logged_in,
  logged_out,
  wrong_password,
  session_timeout,
  expired,
  not_exist,
  error,
  has_placement,
  need_strong_password
}
